package cn.icanci.loopstack.bic.biz.dts;

import java.util.Collection;
import java.util.Map;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

/**
 * @author icanci
 * @since 1.0 Created in 2023/09/17 16:36
 */
@Service
@SuppressWarnings("all")
public class GraphDtsServiceProxy implements GraphDtsService<Object>, ApplicationContextAware {

    private final Map<Class<?>, GraphDtsService> graphDtsServiceMap = Maps.newConcurrentMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, GraphDtsService> beansOfType = applicationContext.getBeansOfType(GraphDtsService.class);
        Collection<GraphDtsService> services = beansOfType.values();
        for (GraphDtsService service : services) {
            DTS dts = AopUtils.getTargetClass(service).getAnnotation(DTS.class);
            if (dts != null) {
                graphDtsServiceMap.put(dts.value(), service);
            }
        }
    }

    @Override
    public void dtsUnitViewTree(Object type) {
        if (type == null) {
            throw new RuntimeException("type is null");
        }

        GraphDtsService graphDtsService = graphDtsServiceMap.get(type.getClass());
        if (graphDtsService == this || graphDtsService == null) {
            throw new RuntimeException(type.getClass() + " is not support");
        }
        graphDtsService.dtsUnitViewTree(type);
    }
}
